package com.itliang.utils;

import com.itliang.core.model.entity.system.SysMenu;

import java.util.ArrayList;
import java.util.List;

/**
 * 根据菜单数据构建菜单树的工具类
 *
 * @author : liangzhuoyuan
 * @createDate : 2023-03-05 8:43
 */
public class MenuHelper {
    public static List<SysMenu> buildTree(List<SysMenu> sysMenuList) {
        List<SysMenu> trees = new ArrayList<>();
        for (SysMenu sysMenu : sysMenuList) {
            // 找到递归入口
            if (sysMenu.getParentId() == 0) {
                trees.add(findChildren(sysMenu, sysMenuList));
            }
        }
        return trees;
    }

    private static SysMenu findChildren(SysMenu sysMenu, List<SysMenu> sysMenuList) {
        sysMenu.setChildren(new ArrayList<>());
        for (SysMenu it : sysMenuList) {
            if (it.getParentId().longValue() == sysMenu.getId().longValue()) {
                if (sysMenu.getChildren() == null) {
                    sysMenu.setChildren(new ArrayList<>());
                }
                sysMenu.getChildren().add(findChildren(it, sysMenuList));
            }
        }
        return sysMenu;
    }
}
